<?php 
/**
 * Joomla! 1.5 component PB-Roster
 *
 * @version $Id: pbroster.php 2010-09-10 10:03:33 svn $
 * @author ML@pixelbyte.dk
 * @package Joomla
 * @subpackage PB-Roster
 * @copyright (C) 2010- pixelbyte.dk
 * @license GNU/GPL
 *
 * A World of Warcraft Guild Roster
 *
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// CURL
class pb_xml_data 
{
  public function get_xml($lang,$url,$throttle)
  {
    // Init cURL
    $ch = curl_init();
		
	// Language
    $header[] = 'Accept-Language: '.$lang;
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
	
	// Throttle requests and try avoid Armory tmp bans.
	if ($throttle)
	  sleep(1);
	
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	$xml = simplexml_load_string($url_string);
	
	// Enable logging
	//print_r($xml);
	
	curl_close($ch);
    return $xml;
  }
}

// Battle.net
class pb_raw_bnet_data 
{
  public function get_guild_data($url) 
  {
    // Init cURL
    $ch = curl_init();
	//echo $url;

	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	/*
	 * Regular Expression 	Will match
	 * foo 					The string "foo"
	 * ^foo 				"foo" at the start of a string
	 * foo$ 				"foo" at the end of a string
	 * ^foo$ 				"foo" when it is alone on a string
	 * [abc] 				a, b, or c
	 * [a-z] 				Any lowercase letter
	 * [^A-Z] 				Any character that is not a uppercase letter
	 * (gif|jpg) 			Matches either "gif" or "jpeg"
	 * [a-z]+ 				One or more lowercase letters
	 * [0-9\.\-] 			Any number, dot, or minus sign
	 * ^[a-zA-Z0-9_]{1,}$ 	Any word of at least one letter, number or _
	 * ([wx])([yz]) 		wy, wz, xy, or xz
	 * [^A-Za-z0-9] 		Any symbol (not a number or a letter)
	 * ([A-Z]{3}|[0-9]{4}) 	Matches three letters or four numbers
	 */
	 
	// Debug
	/*$doc = new DOMDocument();
	$doc->loadHtml($url_string);
    echo $doc->saveHTML();*/
	
	$guild = new stdClass();
    $guild->level = 0;
    $guild->achievement = 0;
	$guild->newsid = 0;
	
	//<span class="level"><strong>LEVEL</strong></span>
	if (preg_match('/<span class="level"><strong>([0-9]+)<\/strong><\/span>/s', $url_string, $matches)) {
	  $guild->level = $matches[1];
	}
	// <div class="achievements"><a href="/wow/en/guild/GUILD-SERVER/GUILD NAME/achievement">330</a></div>
	if (preg_match('/<div class="achievements"><a href="(.*?)">([0-9]+)<\/a><\/div>/s', $url_string, $matches)) {
	  $guild->achievement = $matches[2];
	}
	// <ul class="activity-feed activity-feed-wide"><li data-id="2719672" class="item-purchased first"><dl>
	//if (preg_match('/<ul class="activity(.*?)"><li data-id="([0-9]+)" class="(.*?)first"><dl>/s', $url_string, $matches)) {
	/*if (preg_match('/<li data-id="([0-9]+)" class="(item-purchased|player-ach|item-crafted|guild-levelup|guild-ach)/s', $url_string, $matches)) {
	  $guild->newsid = $matches[1];
	}*/
	  	
	curl_close($ch);
    return $guild;
  }
  
  public function get_avatar_data($url, $avatarId, $path, $type) 
  {
    if ($type == "profilemain") {
      pb_raw_bnet_data::save_avatar($url.$avatarId.'-profilemain.jpg', $path.str_replace("/","-",$avatarId).'-profilemain.jpg');
	}
	else {
      // Init cURL
      $ch = curl_init();
	
	  // Language
      $header[] = 'Accept-Language: en-gb';
	
	  // Browser
	  $browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	  // cURL options
      curl_setopt ($ch, CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
      curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
	  sleep(1); // Throttle
      $url_string = curl_exec($ch);
	
	  // Disable standard libxml errors and enable user error handling.
	  libxml_use_internal_errors(true);
	
	  $doc = new DOMDocument();
	  @$doc->loadHTML($url_string);
	
	  $tags = $doc->getElementsByTagName('img');
	  $i=0;
	  foreach ($tags as $tag) {
	    if ($i==0) {
	      pb_raw_bnet_data::save_avatar($tag->getAttribute('src'), $path.str_replace("/","-",$avatarId).'-'.$type.'.jpg');
		  //echo $tag->getAttribute('src');
	    }
	    $i++;
	  }
	  curl_close($ch);
    }
  }
  
  function save_avatar($img, $fullpath){
  
    $ch = curl_init ($img);
  
    if (file_exists($fullpath)) {
      unlink($fullpath);
    }
    $fp = fopen($fullpath,'w');

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    curl_setopt($ch, CURLOPT_FILE, $fp);

    $rawdata=curl_exec($ch);
    curl_close ($ch);
    fclose($fp);

    // Sometimes the image have not been rendered and returns a doc have been moved.
    $check_img = @getimagesize($fullpath);
    if(!is_array($check_img))
	  unlink($fullpath); // Not an image so we remove it
	
  }
  
  public function test_data($url) 
  {
    // Init cURL
    $ch = curl_init();
	echo $url;
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
	sleep(1); // Throttle
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	// <li data-id="2719672" class="item-purchased first">
	//if (preg_match('/<li data-id="([0-9]+)"/s', $url_string, $matches)) {
	if (preg_match('/<li data-id="([0-9]+)" class="(item-purchased|player-ach|item-crafted|guild-levelup|guild-ach)/s', $url_string, $matches)) {
	  echo '<br />'.$matches[1];
	}

	curl_close($ch);
  }
  
  public function test_data2($url, $amount) 
  {
    // Init cURL
    $ch = curl_init();
	//echo $url;
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
	sleep(1); // Throttle
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	$dom = new domDocument;
    @$dom->loadHTML($url_string);
    $dom->preserveWhiteSpace = false;
	
	//echo $dom->saveHTML();

	$xpath = new DOMXPath( $dom );
	
	$aName = $xpath->query('//div/ul/li/dl');
	
	echo '<ul class="activity-feed activity-feed-wide">';
	$i = 0;
	foreach ( $aName as $data ) {
	  if ($i >= $amount) {
	    // do nothing
	  }
	  else {
		$news = new stdClass();
		$news->name = "";
		$news->type = "";
		$news->str = "";
		$news->time = "";
		$news->time_str = "";
		$news->icon = "";
		
		$news_str = "";
		$type = "";
		$link = "";
	  
		$item = new stdClass();
		$item->id = 0;
		$item->q = 0;
		$item->icon = "";
	  
		if ($i == 0)
		  $first = " first";
		else
	      $first = "";
		
		// Remove certain parts we dont want first
		$string1 = preg_replace('/\s\s+/', ' ', $data->nodeValue); // Remove extra spaces
		$string2 = preg_replace( '/ \((Cloth|Leather|Mail|Plate|Shield|Weapon), item level ([0-9]+)\)./', '.', $string1 );
		$string3 = preg_replace( '/ for ([0-9]+) points./', '.', $string2 );
		$string4 = preg_replace( '/ Level ([0-9]+) Reach level ([0-9]+)./', '', $string3 );
		$string5 = preg_replace( '/ Guild Level ([0-9]+) Reach guild level ([0-9]+)./', '', $string4 );
	  
		//echo utf8_decode($string5) . "<br />\n";
	  
		if (preg_match('/(.*?) (obtained|crafted item|earned the achievement|purchased item|reached level) (.*?). ([0-9]+) (days|hours|minutes|seconds) ago/', $string5, $matches)) {
	      $news->name = utf8_decode(trim($matches[1]));
		  $news->type = $matches[2];
		  $news->str = $matches[3];
		  $news->time = $matches[4];
		  $news->time_str = $matches[5];
		}
	  
		switch ($news->type) {
	      case 'obtained' : 				$link = "item"; 		$type = "item-purchased";	break;
		  case 'crafted item' : 			$link = "item"; 		$type = "item-crafted";		break;
		  case 'earned the achievement' :	$link = "achievements";	if ($news->name = "The guild") {$type = "guild-ach";}else{$type = "player-ach";}	break;
		  case 'purchased item' : 			$link = "item";			$type = "item-purchased";	break;
		  case 'reached level' :			$link = "achievements";	if ($news->name = "The guild") {$type = "guild-levelup";}else{$type = "player-ach";}	break;
		}

		if ($news->name != "") {
		
		  // Get id from wowhead based on string
		  if ($link == "item") {
		    $item = pb_raw_bnet_data::get_wowhead_id(str_replace(" ","+",$news->str));
			$news->icon = '<a class="color-q'.$item->q.'" href="http://www.wowhead.com/'.$link.'='.$item->id.'"><span class="icon-frame frame-18" style="background-image: url(http://static.wowhead.com/images/wow/icons/small/'.$item->icon.'.jpg);"></span></a>';
	        $news_str = '<a class="color-q'.$item->q.'" href="http://www.wowhead.com/'.$link.'='.$item->id.'">'.$news->str.'</a> ';
		  }
		  else {
		    $news->icon = "";
	        $news_str = $news->str;
		  }
		
		  if ($news->name != "The guild") {
		    $char_link = '<a class="color-c'.return_class_id($news->name).'" href="'.JRoute::_('index.php?option=com_pbroster&view=character&ch='.$news->name).'">'.$news->name.'</a>';
		  }
		  else {
		    $char_link = $news->name;
		  }

	      echo '<li class="'.$type.$first.'"><dl><dd>';
		  echo $news->icon;
	      echo $char_link.' '.$news->type.' ';
	      echo $news_str.' ';
		  echo '</dd><dt>';
	      echo $news->time.' '.$news->time_str.' ago.'. "</dt></dl></li>\n";
		  
		  $i++; // only set counter if something valid is found like name.
	    }
	  }
	}
	echo '</ul>';

	curl_close($ch);
  }
  
  public function test_data3($url, $amount) 
  {
    // Init cURL
    $ch = curl_init();
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
	sleep(1); // Throttle
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	$dom = new domDocument;
    @$dom->loadHTML($url_string);
	
	$xpath = new DOMXPath( $dom );
	
	$innerHTML = '';
	foreach ($xpath->getElementsByTagName('p')->item(0)->childNodes as $child) {
      $innerHTML .= $xpath->saveXML($child);
	}
	echo $innerHTML;

	curl_close($ch);
  }
  
  public function get_avatar_id($url) 
  {
    // Init cURL
    $ch = curl_init();
	//echo $url;
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	$id = "";
	
	//<img src="http://eu.battle.net/static-render/eu/steamwheedle-cartel/21/44724245-avatar.jpg?alt=/wow/static/images/2d/avatar/3-1.jpg" alt="" width="56" height="56"/>
	if (preg_match('/<img src="(.*?)\/([0-9]+)\/([0-9]+)-avatar.jpg/s', $url_string, $matches)) {
	  $id = $matches[2].'/'.$matches[3];
	}
	
	curl_close($ch);
	return $id;
  }
  
  public function get_wowhead_id($name, $type='item') 
  {
    // Init cURL
    $ch = curl_init();
	
	$url = 'http://www.wowhead.com/'.$type.'='.$name.'&xml';
	
	//echo $url;
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	$xml = simplexml_load_string($url_string);
	
	//print_r($xml);
	$item = new stdClass();
	$item->id = 0;
	$item->q = 0;
	$item->icon = "";
	
	foreach($xml as $item) {
      $item->id = $item['id'];
	  $item->q = $item->quality['id'];
	  $item->icon = $item->icon;
    }

	curl_close($ch);
	return $item;
  }
  
  public function get_news($url) 
  {
    // Init cURL
    $ch = curl_init();
	//echo $url;
	
	// Language
    $header[] = 'Accept-Language: en-gb';
	
	// Browser
	$browser = 'Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.1)';
	
	// cURL options
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt ($ch, CURLOPT_USERAGENT, $browser);
    $url_string = curl_exec($ch);
	
	// Disable standard libxml errors and enable user error handling.
	libxml_use_internal_errors(true);
	
	// Debug
	$doc = new DOMDocument();
	$doc->loadHtml($url_string);
    echo $doc->saveHTML();
	
	curl_close($ch);
  }
  
}

// Return Component path's
function getRosterPath($option) {
  $path = "";
  switch ($option) {
      case 'base':   $path = JUri::root(true);  break;
      case 'path':   $path = JUri::root();  break;
	  case 'roster': $path = JUri::root().'components/com_pbroster/';  break;
	  case 'emblem': $path = JUri::root().'components/com_pbroster/guild_emblem/';  break;
      case 'images': $path = JUri::root().'components/com_pbroster/images/';  break;
	  default:       $path = JUri::root();  break;
    }
    return $path;
}

/*function createAvatar($name) {
  $path = JPATH_SITE.DS.'componentsx/com_pbroster/images/avatars/';

  $test_guild_data = new pb_raw_bnet_data();
  $avatar = $test_guild_data->get_avatar_data("http://eu.battle.net/wow/en/character/steamwheedle-cartel/".$name."/tooltip", $name, $path);
}*/

function hasPBTemplate() {

  //$has_template = 0;
  $config = getGuildConfig();
  
  if ($config->enable_pbtheme == "yes")
    $has_template = 1;
  else
    $has_template = 0;
  return $has_template;
}

function isMemberLoggedIn() {
    $user =& JFactory::getUser();
    if($user->id) {
      return true;
    }
    else {
      return false;
    }
}

function array_minus_array($a, $b) {
  $c = array_diff($a, $b);
  $c = array_intersect($c, $a);
  return $c;
}

function characterRedirectContent($name) {
    $hasquote = 0;
	$txt = "";
	// Random loading message
	if (getPlugin('quotes')) {
	  if (enabledPluginQuotes()) {
		$txt = randQuote();
	  }
	  else
	    $txt = "";
	}
    echo '<div id="'.$name.'" class="popup_block"><div id="displayMessage">';
	echo '<span class="text">Loading '.$name.'...</span>';
	echo '<span class="quote"><span class="quote-start"></span>'.$txt.'<span class="quote-end"></span></span>';
	echo '<span class="redirect">'.JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_REDIRECT' ).'</span>';
	echo '<div class="pre_loader"><img src="'.getRosterPath("images").'loaders/preload.gif"></div></div></div>';
}

function getXMLData() {

  $ginfo = getGuildInfo();
  $guild = new stdClass();
  $guild->name = "";
  $guild->realm = "";
  $guild->region = "";
  $guild->lang = "";

  foreach ( $ginfo as $row ) {
    $guild->name = $row->name;
    $guild->realm = $row->realm;
    $guild->region = $row->region;
	$guild->lang = $row->lang;
  }
  // Replace spaces with +
  $guild->realm = str_replace(" ","+",$guild->realm);
  $guild->name = str_replace(" ","+",$guild->name);
  
  if ($guild->region == "eu")
	$guild->armory_server = "http://eu.battle.net/";
  else
	$guild->armory_server = "http://us.battle.net/";

  return $guild;
}

function getGuildEmblemType() {

  $ginfo = getGuildInfo();
  $emblem_type = 0;

  foreach ( $ginfo as $row ) {
    $emblem_type = $row->emblem_type;
  }
  return $emblem_type;
}

function get_url_contents($url){
  $crl = curl_init();
  $timeout = 5;
  curl_setopt ($crl, CURLOPT_URL,$url);
  curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
  $ret = curl_exec($crl);
  curl_close($crl);
  return $ret;
}

function parse_query($var) {
 /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = parse_url($var, PHP_URL_QUERY);
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val) {
    $x          = explode('=', $val);
    @$arr[$x[0]] = $x[1];
  }
  unset($val, $x, $var);
  return $arr;
}

function get_category_by_num($xml,$num)  
{  
  foreach($xml->category as $cat)
  {
    foreach($cat->achievement as $ach)
    {  
      if($ach['id'] == $num)  
        return $ach;
    }
  }  
}

function dateDiff($time1, $time2, $precision = 6) {

  // Set timezone
  date_default_timezone_set("Europe/Copenhagen");
 
  // Time format is UNIX timestamp or
  // PHP strtotime compatible strings

    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }
 
    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }
 
    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();
 
    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Set default diff to 0
      $diffs[$interval] = 0;
      // Create temp time from time1 and interval
      $ttime = strtotime("+1 " . $interval, $time1);
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
	$time1 = $ttime;
	$diffs[$interval]++;
	// Create new temp time from time1 and interval
	$ttime = strtotime("+1 " . $interval, $time1);
      }
    }
 
    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
	break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
	// Add s if value is not 1
	if ($value != 1) {
	  $interval .= "s";
	}
	// Add value and interval to times array
	$times[] = $value . " " . $interval;
	$count++;
      }
    }
	
	// Multi-Language support
	$times = str_replace("years",JText::_( 'COM_PBROSTER_DATE_TIME_YEARS' ),$times);
	$times = str_replace("year",JText::_( 'COM_PBROSTER_DATE_TIME_YEAR' ),$times);
	$times = str_replace("months",JText::_( 'COM_PBROSTER_DATE_TIME_MONTHS' ),$times);
	$times = str_replace("month",JText::_( 'COM_PBROSTER_DATE_TIME_MONTH' ),$times);
	$times = str_replace("days",JText::_( 'COM_PBROSTER_DATE_TIME_DAYS' ),$times);
	$times = str_replace("day",JText::_( 'COM_PBROSTER_DATE_TIME_DAY' ),$times);
	$times = str_replace("hours",JText::_( 'COM_PBROSTER_DATE_TIME_HOURS' ),$times);
	$times = str_replace("hour",JText::_( 'COM_PBROSTER_DATE_TIME_HOUR' ),$times);
	$times = str_replace("minutes",JText::_( 'COM_PBROSTER_DATE_TIME_MINUTES' ),$times);
	$times = str_replace("minute",JText::_( 'COM_PBROSTER_DATE_TIME_MINUTE' ),$times);
	$times = str_replace("seconds",JText::_( 'COM_PBROSTER_DATE_TIME_SECONDS' ),$times);
	$times = str_replace("second",JText::_( 'COM_PBROSTER_DATE_TIME_SECOND' ),$times);
 
    // Return string with times
    return implode(", ", $times);
}

/**
 * convert seconds to hours minutes and seconds
 */
function secondsToWords($secs)
{
  if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
  if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
  if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
  $r.=$secs.' second';if($secs<>1){$r.='s';}
  return $r;
}


function return_cache_color($time) {

    $diff = time() - strtotime($time);
    $diffDays = $diff / 60 / 60 / 24;

	if ($diffDays > 4)
      $color = getRosterPath("images")."icons/bullet_red.png";
	else if ($diffDays > 3)
	  $color = getRosterPath("images")."icons/bullet_orange.png";
	else if ($diffDays > 2)
	  $color = getRosterPath("images")."icons/bullet_yellow.png";
	else if ($diffDays > 1)
	  $color = getRosterPath("images")."icons/bullet_green.png";
	else 
	  $color = getRosterPath("images")."icons/bullet_green.png";

    return $color;
}

function return_rank_color($rankid) {
    switch ($rankid) {
        case  0: $rank = "#C31F1F";      break;
        case  1: $rank = "#CF3A2A";      break;
        case  2: $rank = "#FF6633";      break;
        case  3: $rank = "#CC9900";      break;
        case  4: $rank = "#418741";      break;
		case  5: $rank = "#418741";      break;
		case  6: $rank = "#418741";      break;
		case  7: $rank = "#418741";      break;
		case  8: $rank = "#418741";      break;
		case  9: $rank = "#DDE191";      break;
    }
    return $rank;
}

function return_class_color($classid) {
    switch ($classid) {
        case  1: $class = "#C79C6E";      break;
        case  2: $class = "#F58CBA";      break;
        case  3: $class = "#ABD473";      break;
        case  4: $class = "#FFF569";      break;
        case  5: $class = "#FFFFFF";      break;
        case  6: $class = "#C41F3B";      break;
        case  7: $class = "#2459FF";      break;
        case  8: $class = "#69CCF0";      break;
        case  9: $class = "#9482C9";      break;
        case 11: $class = "#FF7D0A";      break;
    }
    return $class;
}

function return_ilevel_color($level) {

	if ($level >= 359) 		// "Epic" raid ready and above
	  $ilev = "#A335EE";
	else if ($level >= 340) // "blue" heroic
	  $ilev = "#0070FF";
	else if ($level >= 329) // "green" pre heroic
	  $ilev = "#1EFF00";
	else
	  $ilev = "#BAC4CD";	// "white"

    return $ilev;
}

function return_role($role) {
	  
	switch ($role) {
		// Death Knight
        case 'spell_deathknight_bloodpresence': 		$nrol = "tank";		break;
        case 'spell_deathknight_frostpresence': 		$nrol = "dps";		break;
        case 'spell_deathknight_unholypresence': 		$nrol = "dps";		break;
		// Druid
        case 'spell_nature_starfall': 					$nrol = "dps";		break;
        case 'ability_racial_bearform': 				$nrol = "dps";		break;
        case 'spell_nature_healingtouch': 				$nrol = "healer";	break;
		// Hunter
        case 'ability_hunter_bestialdiscipline': 		$nrol = "dps";		break;
        case 'ability_hunter_focusedaim': 				$nrol = "dps";		break;
        case 'ability_hunter_camouflage': 				$nrol = "dps";		break;
		// Mage
        case 'spell_holy_magicalsentry': 				$nrol = "dps";		break;
        case 'spell_fire_firebolt02': 					$nrol = "dps";		break;
        case 'spell_frost_frostbolt02': 				$nrol = "dps";		break;
		// Paladin
        case 'spell_holy_holybolt': 					$nrol = "healer";	break;
        case 'ability_paladin_shieldofthetemplar': 		$nrol = "tank";		break;
        case 'spell_holy_auraoflight': 					$nrol = "dps";		break;
		// Priest
        case 'spell_holy_powerwordshield': 				$nrol = "healer";	break;
        case 'spell_holy_guardianspirit': 				$nrol = "healer";	break;
        case 'spell_shadow_shadowwordpain': 			$nrol = "dps";		break;
		// Rogue
        case 'ability_rogue_eviscerate': 				$nrol = "dps";		break;
        case 'ability_backstab': 						$nrol = "dps";		break;
        case 'ability_stealth': 						$nrol = "dps";		break;
		// Shaman
        case 'spell_nature_lightning': 					$nrol = "dps";		break;
        case 'spell_nature_lightningshield': 			$nrol = "dps";		break;
        case 'spell_nature_magicimmunity': 				$nrol = "healer";	break;
		// Warlock
        case 'spell_shadow_deathcoil': 					$nrol = "dps";		break;
        case 'spell_shadow_metamorphosis': 				$nrol = "dps";		break;
        case 'spell_shadow_rainoffire': 				$nrol = "dps";		break;
		// Warrior
        case 'ability_warrior_savageblow': 				$nrol = "dps";		break;
        case 'ability_warrior_innerrage': 				$nrol = "dps";		break;
        case 'ability_warrior_defensivestance': 		$nrol = "tank";		break;
		
    }
    return $nrol;
}

function return_candualwield($role) {
	  
	switch ($role) {
		// Death Knight
        case 'spell_deathknight_bloodpresence': 		$nrol = false;		break;
        case 'spell_deathknight_frostpresence': 		$nrol = true;		break;
        case 'spell_deathknight_unholypresence': 		$nrol = true;		break;
		// Druid
        case 'spell_nature_starfall': 					$nrol = false;		break;
        case 'ability_racial_bearform': 				$nrol = false;		break;
        case 'spell_nature_healingtouch': 				$nrol = false;		break;
		// Hunter
        case 'ability_hunter_bestialdiscipline': 		$nrol = true;		break;
        case 'ability_hunter_focusedaim': 				$nrol = true;		break;
        case 'ability_hunter_camouflage': 				$nrol = true;		break;
		// Mage
        case 'spell_holy_magicalsentry': 				$nrol = false;		break;
        case 'spell_fire_firebolt02': 					$nrol = false;		break;
        case 'spell_frost_frostbolt02': 				$nrol = false;		break;
		// Paladin
        case 'spell_holy_holybolt': 					$nrol = false;		break;
        case 'ability_paladin_shieldofthetemplar': 		$nrol = false;		break;
        case 'spell_holy_auraoflight': 					$nrol = false;		break;
		// Priest
        case 'spell_holy_powerwordshield': 				$nrol = false;		break;
        case 'spell_holy_guardianspirit': 				$nrol = false;		break;
        case 'spell_shadow_shadowwordpain': 			$nrol = false;		break;
		// Rogue
        case 'ability_rogue_eviscerate': 				$nrol = true;		break;
        case 'ability_backstab': 						$nrol = true;		break;
        case 'ability_stealth': 						$nrol = true;		break;
		// Shaman
        case 'spell_nature_lightning': 					$nrol = false;		break;
        case 'spell_nature_lightningshield': 			$nrol = true;		break;
        case 'spell_nature_magicimmunity': 				$nrol = false;		break;
		// Warlock
        case 'spell_shadow_deathcoil': 					$nrol = false;		break;
        case 'spell_shadow_metamorphosis': 				$nrol = false;		break;
        case 'spell_shadow_rainoffire': 				$nrol = false;		break;
		// Warrior
        case 'ability_warrior_savageblow': 				$nrol = true;		break;
        case 'ability_warrior_innerrage': 				$nrol = true;		break;
        case 'ability_warrior_defensivestance': 		$nrol = false;		break;
		
    }
    return $nrol;
}

// internal id
function return_role_id($role) {
	  
	switch ($role) {
		// Death Knight
        case 'spell_deathknight_bloodpresence': 		$nrol = 1;	break;
        case 'spell_deathknight_frostpresence': 		$nrol = 2;	break;
        case 'spell_deathknight_unholypresence': 		$nrol = 3;	break;
		// Druid
        case 'spell_nature_starfall': 					$nrol = 4;	break;
        case 'ability_racial_bearform': 				$nrol = 5;	break;
        case 'spell_nature_healingtouch': 				$nrol = 6;	break;
		// Hunter
        case 'ability_hunter_bestialdiscipline': 		$nrol = 7;	break;
        case 'ability_hunter_focusedaim': 				$nrol = 8;	break;
        case 'ability_hunter_camouflage': 				$nrol = 9;	break;
		// Mage
        case 'spell_holy_magicalsentry': 				$nrol = 10;	break;
        case 'spell_fire_firebolt02': 					$nrol = 11;	break;
        case 'spell_frost_frostbolt02': 				$nrol = 12;	break;
		// Paladin
        case 'spell_holy_holybolt': 					$nrol = 13;	break;
        case 'ability_paladin_shieldofthetemplar': 		$nrol = 14;	break;
        case 'spell_holy_auraoflight': 					$nrol = 15;	break;
		// Priest
        case 'spell_holy_powerwordshield': 				$nrol = 16;	break;
        case 'spell_holy_guardianspirit': 				$nrol = 17;	break;
        case 'spell_shadow_shadowwordpain': 			$nrol = 18;	break;
		// Rogue
        case 'ability_rogue_eviscerate': 				$nrol = 19;	break;
        case 'ability_backstab': 						$nrol = 20;	break;
        case 'ability_stealth': 						$nrol = 21;	break;
		// Shaman
        case 'spell_nature_lightning': 					$nrol = 22;	break;
        case 'spell_nature_lightningshield': 			$nrol = 23;	break;
        case 'spell_nature_magicimmunity': 				$nrol = 24;	break;
		// Warloc
        case 'spell_shadow_deathcoil': 					$nrol = 25;	break;
        case 'spell_shadow_metamorphosis': 				$nrol = 26;	break;
        case 'spell_shadow_rainoffire': 				$nrol = 27;	break;
		// Warrior
        case 'ability_warrior_savageblow': 				$nrol = 28;	break;
        case 'ability_warrior_innerrage': 				$nrol = 29;	break;
        case 'ability_warrior_defensivestance': 		$nrol = 30;	break;
		
		default: 										$nrol = 0;	break;
		
    }
    return $nrol;
}

function return_class($classid) {
    switch ($classid) {
        case  1: $class = "Warrior";      break;
        case  2: $class = "Paladin";      break;
        case  3: $class = "Hunter";       break;
        case  4: $class = "Rogue";        break;
        case  5: $class = "Priest";       break;
        case  6: $class = "Death Knight"; break;
        case  7: $class = "Shaman";       break;
        case  8: $class = "Mage";         break;
        case  9: $class = "Warlock";      break;
        case 11: $class = "Druid";        break;
		default: $class = "Unknown";      break;
    }
    return $class;
}

function return_class_lang($classid) {
    switch ($classid) {
        case  1: $class = JText::_( 'COM_PBROSTER_CLASS_WARRIOR' );      break;
        case  2: $class = JText::_( 'COM_PBROSTER_CLASS_PALADIN' );      break;
        case  3: $class = JText::_( 'COM_PBROSTER_CLASS_HUNTER' );       break;
        case  4: $class = JText::_( 'COM_PBROSTER_CLASS_ROGUE' );        break;
        case  5: $class = JText::_( 'COM_PBROSTER_CLASS_PRIEST' );       break;
        case  6: $class = JText::_( 'COM_PBROSTER_CLASS_DEATHKNIGHT' );  break;
        case  7: $class = JText::_( 'COM_PBROSTER_CLASS_SHAMAN' );       break;
        case  8: $class = JText::_( 'COM_PBROSTER_CLASS_MAGE' );         break;
        case  9: $class = JText::_( 'COM_PBROSTER_CLASS_WARLOCK' );      break;
        case 11: $class = JText::_( 'COM_PBROSTER_CLASS_DRUID' );        break;
		default: $class = "";      										 break;
    }
    return $class;
}

function return_race_gender($raceid, $sex) {
    switch ($raceid) {
        case 1:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_HUMAN_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_HUMAN_FEMALE' );}
            break;
        case 2:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_ORC_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_ORC_FEMALE' );}
            break;
        case 3:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_DWARF_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_DWARF_FEMALE' );}
            break;
        case 4:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_NIGHTELF_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_NIGHTELF_FEMALE' );}
            break;
        case 5:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_UNDEAD_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_UNDEAD_FEMALE' );}
            break;
        case 6:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_TAUREN_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_TAUREN_FEMALE' );}
            break;
        case 7:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_GNOME_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_GNOME_FEMALE' );}
            break;
        case 8:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_TROLL_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_TROLL_FEMALE' );}
            break;
        case 9:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_GOBLIN_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_GOBLIN_FEMALE' );}
            break;
        case 10:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_BLOODELF_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_BLOODELF_FEMALE' );}
            break;
        case 11:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_DRAENEI_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_DRAENEI_FEMALE' );}
            break;
		case 22:
            if ($sex == "0") {$race = JText::_( 'COM_PBROSTER_RACE_WORGEN_MALE' );}
            if ($sex == "1") {$race = JText::_( 'COM_PBROSTER_RACE_WORGEN_FEMALE' );}
            break;
		default: $race = ""; break;
    }
    return $race;
}   

function return_race($raceid) {
    switch ($raceid) {
        case  1: $race = "Human";     break;
        case  2: $race = "Orc";       break;
        case  3: $race = "Dwarf";     break;
        case  4: $race = "Night Elf"; break;
        case  5: $race = "Undead";    break;
        case  6: $race = "Tauren";    break;
        case  7: $race = "Gnome";     break;
        case  8: $race = "Troll";     break;
        case  9: $race = "Goblin";    break;
        case 10: $race = "Blood Elf"; break;
        case 11: $race = "Draenei";   break;
		case 22: $race = "Worgen";   break;
    }
    return $race;
}

function return_race_lang($raceid) {
    switch ($raceid) {
        case  1: $race = JText::_( 'COM_PBROSTER_RACE_HUMAN' );     break;
        case  2: $race = JText::_( 'COM_PBROSTER_RACE_ORC' );       break;
        case  3: $race = JText::_( 'COM_PBROSTER_RACE_DWARF' );     break;
        case  4: $race = JText::_( 'COM_PBROSTER_RACE_NIGHTELF' );  break;
        case  5: $race = JText::_( 'COM_PBROSTER_RACE_UNDEAD' );    break;
        case  6: $race = JText::_( 'COM_PBROSTER_RACE_TAUREN' );    break;
        case  7: $race = JText::_( 'COM_PBROSTER_RACE_GNOME' );     break;
        case  8: $race = JText::_( 'COM_PBROSTER_RACE_TROLL' );     break;
        case  9: $race = JText::_( 'COM_PBROSTER_RACE_GOBLIN' );	break;
        case 10: $race = JText::_( 'COM_PBROSTER_RACE_BLOODELF' );  break;
        case 11: $race = JText::_( 'COM_PBROSTER_RACE_DRAENEI' );   break;
		case 22: $race = JText::_( 'COM_PBROSTER_RACE_WORGEN' );    break;
		default: $race = ""; break;
    }
    return $race;
}

function return_gender($genderid) {
    if ($genderid == "0") {$gender = "Male";}
    if ($genderid == "1") {$gender = "Female";}
    return $gender;
}

function return_gender_lang($genderid) {
    if ($genderid == "0") {$gender = JText::_( 'COM_PBROSTER_GENDER_MALE' );}
    if ($genderid == "1") {$gender = JText::_( 'COM_PBROSTER_GENDER_FEMALE' );}
    return $gender;
}

function return_race_faction($raceid) {

    switch ($raceid) {
      case  1: $faction = "alliance";  break;
      case  2: $faction = "horde";     break;
      case  3: $faction = "alliance";  break;
      case  4: $faction = "alliance";  break;
      case  5: $faction = "horde";     break;
      case  6: $faction = "horde";     break;
      case  7: $faction = "alliance";  break;
      case  8: $faction = "horde";     break;
      case  9: $faction = "horde";	   break;
      case 10: $faction = "horde";     break;
      case 11: $faction = "alliance";  break;
	  case 22: $faction = "alliance";  break;
	}
    return $faction;
}

/**
 * Get avatar and fallback to a default image if not found
 */
function return_avatar_src($avatarid, $raceid, $genderid) {
	$jpath = JPATH_SITE.DS.'components/com_pbroster/images/avatars/'.str_replace("/","-",$avatarid.'-avatar.jpg');
	$path = getRosterPath("images").'avatars/';
	$fullpath = $path.str_replace("/","-",$avatarid.'-avatar.jpg');
	//$fullpath = $path.$avatarid.'-avatar.jpg';
    $check_img = @getimagesize($jpath);
    if(!is_array($check_img))
	  $fullpath = $path.'default/'.$raceid.'-'.$genderid.'.jpg'; // Not an image use default
	  
    return $fullpath;
}

// Translate level to spell id used to lookup wowhead tooltip
/*function get_perk_tooltip($level) {

	switch ($level) {
        case  1: $spell = 0;     break;
        case  2: $spell = 78631; break;
        case  3: $spell = 78633; break;
        case  4: $spell = 78634; break;
        case  5: $spell = 83940; break;
		
        case  6: $spell = 78632; break;
        case  7: $spell = 83942; break;
        case  8: $spell = 83944; break;
        case  9: $spell = 83943; break;
        case 10: $spell = 83945; break;
		
        case 11: $spell = 83958; break;
		case 12: $spell = 78635; break;
		case 13: $spell = 83959; break;
		case 14: $spell = 83949; break;
		case 15: $spell = 83950; break;
		
		case 16: $spell = 83941; break;
		case 17: $spell = 83951; break;
		case 18: $spell = 83953; break;
		case 19: $spell = 83960; break;
		case 20: $spell = 83963; break;
		
		case 21: $spell = 83967; break;
		case 22: $spell = 83961; break;
		case 23: $spell = 83966; break;
		case 24: $spell = 83964; break;
		case 25: $spell = 83968; break;
    }
    return $spell;
}*/

/**
 * Wowhead seems really buggy and slow with perk tooltips, so we create our own.
 */
function get_perk_tooltip($level) {

	$perk->name = "";
	$perk->desc = "";

	switch ($level) {
        case  1: $perk->name = "Fast Track";				$perk->desc = "Experience gained from killing monsters and completing quests increased by 5%."; break; // placeholder
        case  2: $perk->name = "Fast Track";				$perk->desc = "Experience gained from killing monsters and completing quests increased by 5%."; break;
        case  3: $perk->name = "Mount Up";					$perk->desc = "Increases speed while mounted by 10%.  Not active in Battlegrounds or Arenas."; break;
        case  4: $perk->name = "Mr. Popularity";			$perk->desc = "Reputation gained from killing monsters and completing quests increased by 5%."; break;
        case  5: $perk->name = "Cash Flow";					$perk->desc = "Each time you loot money from an enemy, an extra 5% money is generated and deposited directly into your guild bank."; break;
		
        case  6: $perk->name = "Fast Track";				$perk->desc = "Experience gained from killing monsters and completing quests increased by 10%."; break;
        case  7: $perk->name = "Reinforce";					$perk->desc = "Items take 10% less durability loss when you die."; break;
        case  8: $perk->name = "Hasty Hearth";				$perk->desc = "Reduces the cooldown on your Hearthstone by 15 minutes."; break;
        case  9: $perk->name = "Reinforce";					$perk->desc = "Items take 20% less durability loss when you die."; break;
        case 10: $perk->name = "Chug-A-Lug";				$perk->desc = "The duration of buffs from all guild cauldrons is increased by 50%."; break;
		
        case 11: $perk->name = "Mobile Banking";			$perk->desc = "Summons a Guild Chest that allows access to your guild bank for 5 min.  Only guildmembers with guild faction of friendly and above are allowed to use a Guild Chest."; break;
		case 12: $perk->name = "Mr. Popularity";			$perk->desc = "Reputation gained from killing monsters and completing quests increased by 10%."; break;
		case 13: $perk->name = "Honorable Mention";			$perk->desc = "Increases Honor points gained by 5%."; break;
		case 14: $perk->name = "Working Overtime";			$perk->desc = "Increases the chance to gain a skill increase on tradeskills by 10%."; break;
		case 15: $perk->name = "The Quick and the Dead";	$perk->desc = "Increases health gained when resurrected by a guild member by 50% and increases movement speed while dead by 100%.  Does not function in combat or while in a Battleground or Arena."; break;
		
		case 16: $perk->name = "Cash Flow";					$perk->desc = "Each time you loot money from an enemy, an extra 10% money is generated and deposited directly into your guild bank."; break;
		case 17: $perk->name = "G-Mail";					$perk->desc = "In-game mail sent between guild members now arrives instantly."; break;
		case 18: $perk->name = "For Great Justice";			$perk->desc = "Increases Justice points gained by 10%."; break;
		case 19: $perk->name = "Honorable Mention";			$perk->desc = "Increases Honor points gained by 10%."; break;
		case 20: $perk->name = "Happy Hour";				$perk->desc = "Increases the number of flasks gained from using a flask cauldron by 50%."; break;
		
		case 21: $perk->name = "Have Group, Will Travel";	$perk->desc = "Summons all raid or party members to the caster's current location.  Cannot be cast in combat or while in a battleground or arena."; break;
		case 22: $perk->name = "Chug-A-Lug";				$perk->desc = "The duration of buffs from all guild cauldrons is increased by 100%."; break;
		case 23: $perk->name = "Bountiful Bags";			$perk->desc = "Increases the quantity of materials gained from Mining, Skinning, Herbalism, and Disenchanting."; break;
		case 24: $perk->name = "Bartering";					$perk->desc = "Reduces the price of items from all vendors by 10%."; break;
		case 25: $perk->name = "Mass Resurrection";			$perk->desc = "Brings all dead party and raid members back to life with 35% health and 35% mana.  A player may only be resurrected by this spell once every 10 minutes.  Cannot be cast in combat or while in a battleground or arena."; break;
    }
    return $perk;
}

function get_wowhead_domain($lang) {
  $domain = "www.";
	  
  if ($lang == "" || $lang == "en-gb" || $lang == "en-us")
	$domain = "www.";
  else if ($lang == "de-de")
	$domain = "de.";
  else if ($lang == "es-es")
	$domain = "es.";
  else if ($lang == "fr-fr")
	$domain = "fr.";
  else if ($lang == "ru-ru")
	$domain = "ru.";
  return $domain;
}

function guild_perk($level) {
	  
	switch ($prof) {
	
        case 'Alchemy': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ALCHEMY' );        break;
        case 'Blacksmithing': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_BLACKSMITHING' );  break;
        case 'Enchanting': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ENCHANTING' );     break;
        case 'Engineering': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ENGINEERING' );    break;
        case 'Inscription': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_INSCRIPTION' );    break;
        case 'Jewelcrafting': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_JEWELCRAFTING' );  break;
        case 'Leatherworking': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_LEATHERWORKING' ); break;
        case 'Tailoring': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_TAILORING' );      break;
        case 'Herbalism': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_HERBALISM' );      break;
        case 'Mining': 			$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_MINING' ); 	       break;
        case 'Skinning': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_SKINNING' );   	   break;
    }
    return $nprof;

} 

function note_prof($prof) {
	  
	$nprof = "?";
	switch ($prof) {
	
        case 'Alchemy': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ALCHEMY' );        break;
        case 'Blacksmithing': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_BLACKSMITHING' );  break;
        case 'Enchanting': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ENCHANTING' );     break;
        case 'Engineering': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_ENGINEERING' );    break;
        case 'Inscription': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_INSCRIPTION' );    break;
        case 'Jewelcrafting': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_JEWELCRAFTING' );  break;
        case 'Leatherworking': 	$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_LEATHERWORKING' ); break;
        case 'Tailoring': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_TAILORING' );      break;
        case 'Herbalism': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_HERBALISM' );      break;
        case 'Mining': 			$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_MINING' ); 	       break;
        case 'Skinning': 		$nprof = JText::_( 'COM_PBROSTER_PLUGIN_MEMBER_NOTES_ABB_SKINNING' );   	   break;
    }
    return $nprof;

}

/**
 * Attempt to make some sort of version control so that both Joomla 1.5 and 1.6 works
 * without the need to make different versions for each.
 */
function getJoomlaUserType() {  
  $version = new JVersion;
  $j_version = substr($version->getShortVersion(), 0, 3);
  if ($j_version == "1.6")
	return getJoomlaUserType16();
  else
	return getJoomlaUserType15();
}

// Joomla 1.5
function getJoomlaUserType15() {
  $user =& JFactory::getUser();
  
  switch ($user->gid) {
	
        case 18: 		$type = "Registered";        	break;
		case 19: 		$type = "Author";        		break;
		case 20: 		$type = "Editor";        		break;
		case 21: 		$type = "Publisher";        	break;
		case 23: 		$type = "Manager";        		break;
		case 24: 		$type = "Administrator";        break;
		case 25: 		$type = "Super Administrator";  break;
		case 29: 		$type = "Public Frontend";      break;
		case 30: 		$type = "Public Backend";       break;
    }
    return $type;
}

// Joomla 1.6
function getJoomlaUserType16() {
  $db = JFactory::getDbo();
  $user =& JFactory::getUser();
  $userid = $user->get( 'id' );
  
  $query = $db->getQuery(true);
  $query->select('g.title AS group_name')
  ->from('#__usergroups AS g')
  ->leftJoin('jos_user_usergroup_map AS map ON map.group_id = g.id')
  ->where('map.user_id = '.(int)$userid);
  $db->setQuery($query);
  $ugp = $db->loadObject();
  
  return $ugp->group_name;
}

function getRosterTemplateAdjust($config){

  $template = new stdClass();
  $template->marginleft = "";
  $template->margintop = "";

  if ($config->roster_padding_left != 0)
	$template->marginleft = 'margin-left:'.$config->roster_padding_left.'px;';
  if ($config->roster_padding_top != 0)
	$template->margintop = 'margin-top:'.$config->roster_padding_top.'px;';
	
  return $template;
}

function demoServerEnabled() {
  //$enabled = true;
  $enabled = false;
  
  return $enabled;
}


?>